import React, { PureComponent } from 'react'
import { Trans, withI18n } from '@lingui/react'
import {
  Button,
  Typography,
  Tooltip,
  Spin,
  Alert,
  Layout,
  Divider,
  Icon,
  Input,
  Row,
  Col,
  Tag,
  List,
} from 'antd'
import { Ellipsis } from 'ant-design-pro'
import actionstyle from './Projectslist.less'
const { Sider } = Layout
const { Paragraph, Title } = Typography
const ButtonGroup = Button.Group

@withI18n()
class Projectlist extends PureComponent {
  state = {
    inputVisible: false,
    input2Visible: false,
    newprojectname: '',
    editablemode: false,
    renamemode: false,
    editingobj: '',
    renameName: '',
  }

  saveInputRef = input => (this.input = input)

  saveInput2Ref = input => (this.input2 = input)

  render() {
    const {
      isMobile,
      projectloading,
      projectaddloading,
      projectrenameloading,
      projects,
      choosedproject,
      onChangeProjectName,
      onClickProject,
      onRefresh,
      onNewProject,
      onDeleteProject,
      i18n,
    } = this.props

    const {
      inputVisible,
      newprojectname,
      editablemode,
      input2Visible,
      renamemode,
      editingobj,
      renameName,
    } = this.state

    const onhandleConfirm = e => {
      // const { value } = e.target;
      onNewProject(newprojectname)
      this.setState({
        input2Visible: false,
        inputVisible: false,
        newprojectname: '',
      })
    }
    const oncancel = e => {
      this.setState({
        input2Visible: false,
        inputVisible: false,
        newprojectname: '',
      })
    }
    const onChange = e => {
      const { value } = e.target
      this.setState({
        newprojectname: value,
      })
    }
    const onRenameConfirm = (e, item) => {
      onChangeProjectName(renameName, item)
      this.setState({
        editingobj: '',
        renameName: '',
      })
    }
    const onRenameChange = e => {
      const { value } = e.target
      this.setState({
        renameName: value,
      })
    }
    const onCancelRename = e => {
      this.setState({
        editingobj: '',
        renameName: '',
      })
    }

    const emptyitem = () => (
      <div style={{ width: '100%' }}>
        <div style={{ textAlign: 'center' }}>
          <img
            alt=""
            src="http://lc-rohmehlw.cn-n1.lcfile.com/ebe1c69d8a473f5fb2ba.png"
            style={{ width: '90px', height: '80px' }}
          />
        </div>
      </div>
    )

    const titleprojectitems = item => {
      // let recycle = item.objectId == 'recycle'
      let staticitem = item.objectId == 'all' || item.objectId == 'EMPTY'
      let devicecount = item.count
      const name = item.ProjectName
      let choosed = choosedproject == item.objectId
      let choosedstyle = choosed
        ? {
            fontSize: '15px',
            cursor: 'not-allowed',
            color: '#8fc9fb',
            margin: '0px',
            marginTop: '0px',
            padding: '0px',
          }
        : {
            fontSize: '15px',
            cursor: 'pointer',
            ...(devicecount == 0 ? {} : { color: 'rgb(128,128,128)' }),
            margin: '0px',
            marginTop: '0px',
            padding: '0px',
          }

      return (
        <Tooltip
          placement="right"
          title={i18n.t`${name} includes ${devicecount} equipment`}
        >
          <Paragraph
            {...(devicecount == 0 ? { disabled: true } : {})}
            {...(staticitem ? { strong: true } : {})}
            onClick={e => onClickProject(e, item, choosed)}
            style={{ ...choosedstyle }}
          >
            {item.ProjectName}
          </Paragraph>
        </Tooltip>
      )
    }

    const projectitem = item => {
      let recycle = item.objectId == 'recycle'
      let choosed = choosedproject == item.objectId
      let staticitem = item.objectId == 'all' || item.objectId == 'EMPTY'
      let devicecount = item.count
      let choosedstyle = choosed
        ? {
            fontSize: '15px',
            cursor: 'not-allowed',
            color: '#8fc9fb',
            margin: '0px',
            marginRight: '0px',
            padding: '0px',
          }
        : {
            fontSize: '15px',
            cursor: 'pointer',
            ...(devicecount == 0 ? {} : { color: 'rgb(128,128,128)' }),
            margin: '0px',
            marginRight: '0px',
            padding: '0px',
          }
      const actionmodel = (judge2, iconname, title2, onClick) =>
        choosed ? (
          <Tooltip
            placement="top"
            title={i18n.t`You have selected this project. Please cancel the selection and operate it`}
          >
            <Icon type={iconname} />
          </Tooltip>
        ) : judge2 ? (
          <Icon
            type={iconname}
            theme="twoTone"
            style={{ cursor: 'pointer' }}
            onClick={onClick}
          />
        ) : (
          <Tooltip placement="top" title={title2}>
            <Icon type={iconname} />
          </Tooltip>
        )
      let action = editablemode ? (
        actionmodel(
          item.deleteable,
          'delete',
          i18n.t`You have no right to delete this item`,
          e => {
            onDeleteProject(item)
          }
        )
      ) : renamemode ? (
        actionmodel(
          item.editable,
          'edit',
          i18n.t`You have no right to rename this item`,
          e => {
            this.setState(
              { editingobj: item.objectId, renameName: item.ProjectName },
              () => {
                this.input2.focus()
              }
            )
          }
        )
      ) : (
        <div style={{ margin: '0px', padding: '0px' }}>{item.count}</div>
      )

      let ellipcount = editablemode || renamemode ? 6 : 8
      let name = item.ProjectName
      return (
        <List.Item
          className={actionstyle.customaction}
          {...(editingobj == item.objectId ? {} : { actions: [action] })}
          style={{ margin: '0px', padding: '0px', paddingBottom: '5px' }}
        >
          {editingobj == item.objectId ? (
            <Tooltip
              trigger="focus"
              placement="topLeft"
              title={i18n.t`Press Enter to confirm`}
            >
              <Input
                value={renameName}
                ref={this.saveInput2Ref}
                size="small"
                style={{ width: '100%', marginRight: '2px' }}
                onChange={onRenameChange}
                onPressEnter={e => {
                  onRenameConfirm(e, item)
                }}
                onBlur={onCancelRename}
                disabled={projectrenameloading}
              />
            </Tooltip>
          ) : (
            <Tooltip
              placement="right"
              title={i18n.t`The ${name} project includes ${devicecount} equipment`}
            >
              <Ellipsis
                // {...(devicecount == 0 ? { disabled: true } : {})}
                // {...(staticitem
                //   ? { strong: true }
                //   : recycle
                //     ? { type: 'danger' }
                //     : {})}
                onClick={e => onClickProject(e, item, choosed)}
                lines={1}
                style={{ ...choosedstyle, width: '100%' }}
              >
                {/* {name.length > ellipcount
                    ? name.slice(0, ellipcount) + '..'
                    : name} */}
                {name}
              </Ellipsis>
            </Tooltip>
          )}
        </List.Item>
      )
    }

    const mobiletitleitem = item => {
      let choosed = choosedproject == item.objectId
      let name = item.ProjectName
      let devicecount = item.count
      return (
        <Tooltip
          placement="top"
          title={i18n.t`The ${name} project includes ${devicecount} equipment`}
        >
          <Tag
            {...(choosed ? { color: 'blue' } : {})}
            style={{ marginBottom: '5px', marginRight: '5px' }}
            onClick={e => {
              onClickProject(e, item, choosed)
            }}
          >
            <Icon type="folder" style={{ marginRight: '5px' }} />
            {item.ProjectName}&nbsp;&nbsp;&nbsp;{item.count}
          </Tag>
        </Tooltip>
      )
    }

    const mobileprojectitem = item => {
      let choosed = choosedproject == item.objectId
      let name = item.ProjectName
      let devicecount = item.count
      let ellipcount = 10
      const ellipname =
        name.length > ellipcount ? name.slice(0, ellipcount) + '..' : name
      const actionmodel = (judge2, iconname, title2, onClick) =>
        choosed ? (
          <Tooltip
            placement="top"
            title={i18n.t`You have selected this project. Please cancel the selection and operate it`}
          >
            <Tag style={{ marginBottom: '5px', marginRight: '5px' }}>
              <Icon type={iconname} style={{ marginRight: '5px' }} />
              {ellipname}&nbsp;&nbsp;&nbsp;{devicecount}
            </Tag>
          </Tooltip>
        ) : judge2 ? (
          <Tag
            color="blue"
            style={{ marginBottom: '5px', marginRight: '5px' }}
            onClick={onClick}
          >
            <Icon type={iconname} style={{ marginRight: '5px' }} />
            {ellipname}&nbsp;&nbsp;&nbsp;{devicecount}
          </Tag>
        ) : (
          <Tooltip placement="top" title={title2}>
            <Tag style={{ marginBottom: '5px', marginRight: '5px' }}>
              <Icon type={iconname} style={{ marginRight: '5px' }} />
              {ellipname}&nbsp;&nbsp;&nbsp;{devicecount}
            </Tag>
          </Tooltip>
        )
      return editingobj == item.objectId ? (
        <Tooltip
          trigger="focus"
          placement="top"
          title={i18n.t`Press Enter to confirm`}
        >
          <Input
            value={renameName}
            ref={this.saveInputRef}
            size="small"
            style={{ width: '100px', marginRight: '2px' }}
            onChange={onRenameChange}
            onPressEnter={e => {
              onRenameConfirm(e, item)
            }}
            onBlur={onCancelRename}
            disabled={projectrenameloading}
          />
        </Tooltip>
      ) : editablemode ? (
        actionmodel(
          item.deleteable,
          'delete',
          i18n.t`You have no right to delete this item`,
          e => {
            onDeleteProject(item)
          }
        )
      ) : renamemode ? (
        actionmodel(
          item.editable,
          'edit',
          i18n.t`You have no right to rename this item`,
          e => {
            this.setState(
              { editingobj: item.objectId, renameName: item.ProjectName },
              () => {
                this.input.focus()
              }
            )
          }
        )
      ) : (
        <Tooltip
          placement="top"
          title={i18n.t`The ${name} project includes ${devicecount} equipment`}
        >
          <Tag
            {...(choosed ? { color: 'blue' } : {})}
            style={{ marginBottom: '5px', marginRight: '5px' }}
            onClick={e => onClickProject(e, item, choosed)}
          >
            <Icon type={'folder'} style={{ marginRight: '5px' }} />
            {ellipname}&nbsp;&nbsp;{devicecount}
          </Tag>
        </Tooltip>
      )
    }

    const description = () => (
      <div>
        <Divider style={{ marginTop: '5px', marginBottom: '10px' }} />
        {projects.slice(0, 2).map(item => titleprojectitems(item))}
        {projects.length > 2 && (
          <p style={{ marginTop: '5px' }}>
            {input2Visible ? (
              <Tooltip
                trigger="focus"
                placement="topLeft"
                title={i18n.t`Press Enter to confirm`}
              >
                <Input
                  value={newprojectname}
                  ref={this.saveInput2Ref}
                  size="small"
                  style={{ width: '100%' }}
                  onChange={onChange}
                  onPressEnter={onhandleConfirm}
                  onBlur={oncancel}
                  disabled={projectaddloading}
                />
              </Tooltip>
            ) : (
              <Button
                size="small"
                type="dashed"
                block
                onClick={e => {
                  this.setState({ input2Visible: true }, () =>
                    this.input2.focus()
                  )
                }}
              >
                <Trans>Create Project</Trans>
              </Button>
            )}
          </p>
        )}
        <Divider style={{ marginTop: '5px', marginBottom: '10px' }} />
        {projects.length <= 2 ? (
          emptyitem()
        ) : (
          <div style={{ overflow: 'scroll', maxHeight: '500px' }}>
            <List
              style={{ overflow: 'scroll', maxHeight: '500px' }}
              split={false}
              dataSource={projects.slice(2, projects.length)}
              // itemLayout="horizontal"
              // itemLayout="verical"
              renderItem={item => projectitem(item)}
              style={{}}
              size="small"
            />
          </div>
        )}
      </div>
    )

    const mobiledescription = () => (
      <div>
        {!editablemode && !renamemode && (
          <div>
            {projects.slice(0, 2).map(item => {
              return mobiletitleitem(item)
            })}
          </div>
        )}
        <div>
          {projects && projects.length <= 2
            ? emptyitem()
            : projects.slice(2, projects.length).map(item => {
                return mobileprojectitem(item)
              })}
          {!editablemode &&
            !renamemode &&
            projects &&
            projects.length > 2 &&
            (inputVisible ? (
              <Tooltip
                trigger="focus"
                placement="topLeft"
                title={i18n.t`Press Enter to confirm`}
              >
                <Input
                  value={newprojectname}
                  ref={this.saveInputRef}
                  size="small"
                  style={{ width: '100px' }}
                  onChange={onChange}
                  onPressEnter={onhandleConfirm}
                  onBlur={oncancel}
                  disabled={projectaddloading}
                />
              </Tooltip>
            ) : (
              <Tag
                disabled={projectaddloading}
                style={{
                  marginBottom: '5px',
                  marginRight: '5px',
                  background: '#fff',
                  borderStyle: 'dashed',
                }}
                onClick={e =>
                  this.setState({ inputVisible: true }, () =>
                    this.input.focus()
                  )
                }
              >
                <Icon type={'plus'} style={{ marginRight: '5px' }} />
                <Trans>Create Project</Trans>
              </Tag>
            ))
          // <Button size="small" type="dashed" onClick={e => { this.setState({ input2Visible: true }, () => this.input2.focus()); }}><Trans>Create Project</Trans></Button>
          }
        </div>
      </div>
    )

    const buttongroups = style => (
      <Tooltip placement="top" title={i18n.t`Refresh`}>
        <Button
          size="small"
          onClick={e => onRefresh()}
          style={{ margin: 0, ...style }}
        >
          <Icon type={projectloading ? 'loading' : 'sync'} />
        </Button>
      </Tooltip>
    )

    const projectscontent = description => (
      <Alert
        message={
          isMobile ? (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Title
                level={4}
                style={{ display: 'inline-block', marginRight: '10px' }}
              >
                <Trans>Projects List</Trans>:
              </Title>
              {buttongroups()}
            </div>
          ) : (
            // <Row gutter={24}>
            //   <Col span={14}>

            //   </Col>
            //   <Col span={10}></Col>
            // </Row>
            <span style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Title
                level={4}
                style={{ display: 'inline-block', marginRight: '10px' }}
              >
                <Trans>Projects List</Trans>
              </Title>
              {buttongroups()}
            </span>
          )
        }
        description={description}
        type="info"
        style={{
          background: '#fff',
          borderColor: isMobile ? 'rgb(244,244,244)' : '#fff',
          margin: '0px',
          marginBottom: '10px',
          marginTop: '0px',
          paddingTop: isMobile ? '12px' : '0px',
        }}
      />
    )

    return (
      <Spin spinning={projectloading}>
        {isMobile ? (
          projectscontent(mobiledescription())
        ) : (
          <Sider width={150} style={{ background: '#fff' }}>
            {projectscontent(description())}
          </Sider>
        )}
      </Spin>
    )
  }
}

export default Projectlist
